package com.base.schedule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @Author:sjb
 * @CreateTime:2024-08-29
 * @Description: 定时任务测试类
 * @Version：1.0
 */
@Component
public class ScheduleTest {

    private static final Logger log = LoggerFactory.getLogger(ScheduleTest.class);

    //@Scheduled(cron = "30 * * * * ?")
    public void testScheduleList() {
        List<String> iteratorConditionList = new ArrayList<>();
        iteratorConditionList.add("ceshi");
        String date = "20240829";
        Date handleSjDate = handleSjDate(date);

        // 打印日期和条件检查结果
        System.out.println("Date to handle: " + handleSjDate);
        boolean createTimeToday = isCreateTimeToday(handleSjDate);
        System.out.println("Is createTimeToday? " + createTimeToday);

        // 临时存储要添加的元素
        List<String> toAdd = new ArrayList<>();

        Iterator<String> stringIterator = iteratorConditionList.iterator();
        while (stringIterator.hasNext()) {
            // 打印当前迭代的元素
            String element = stringIterator.next();
            System.out.println("Current element: " + element);
            if (createTimeToday) {
                toAdd.add("createTimeToday");
            }
        }
        // 在迭代完成后再添加元素
        iteratorConditionList.addAll(toAdd);
        System.out.println("-------------");
        System.out.println("Elements to add:");
        toAdd.forEach(System.out::println);
        System.out.println("Final iteratorConditionList:");
        iteratorConditionList.forEach(System.out::println);
    }


    public static boolean isCreateTimeToday(Date createTime) {
        // 获取今天的日期
        LocalDate today = LocalDate.now();

        // 将 createTime 转换为 LocalDate
        LocalDate createTimeDate = createTime.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        // 比较日期是否相等
        return today.equals(createTimeDate);
    }

    public Date handleSjDate(String sjDate){
        String year = sjDate.substring(0, 4);
        String month = sjDate.substring(4, 6);
        String day = sjDate.substring(6, 8);

        String dateString = year + "-" + month + "-" + day;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(dateString);
        } catch (ParseException e) {
            log.error("Error parsing date: " + dateString);
            e.printStackTrace();
        }
        return date;
    }
}
